//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.IO;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;

namespace CommunityServer.Controls 
{

	public class RoleIcons : UserInfo 
	{

		#region Render functions
		protected override void Render(HtmlTextWriter writer) 
		{

			// if the user is anonymous or we don't have a roleID, return
			if((RoleID == null) && (User.IsAnonymous) || IsCloakedUser)
				return;

			ArrayList roles;
			LiteralControl literal = new LiteralControl("<br>");
			HtmlAnchor anchor;
			Image image;

			// if we have an id we can skip some work
			if(RoleID != null)
			{
				roles = new ArrayList();
				roles.Add( Roles.GetRole( new Guid(RoleID) ) );
			}
			else
			{
				roles = Roles.GetRoles(this.User.UserID, true);
			}

			// Loop though the user's roles and render the controls
			foreach(Role role in roles)
			{
				string roleIDString = role.RoleID.ToString().Replace(" ", "_");

				// Determine whether the image exists in any of the acceptable locations
                string vpath = GetRoleImage(roleIDString);

				if( !Globals.IsNullorEmpty(vpath) ) 
				{
					if (this.EnablePadding)
						writer.Write( Formatter.Whitespace(2, 0, false, true) );
					else
						writer.Write(" ");

					image = new Image();

					image.AlternateText = role.Name;
					image.ImageUrl = vpath;

					if (this.EnablePadding)
						literal.RenderControl(writer);

					if (this.EnableLink)
					{
						anchor = new HtmlAnchor();

						if (this.Target != null)
							anchor.Target = this.Target;

						anchor.Controls.Add(image);
						anchor.HRef = Globals.GetSiteUrls().UserRoles( role.RoleID.ToString() );
						anchor.RenderControl(writer);
					}
					else
					{
						image.RenderControl(writer);
					}

				}
			}
		}

		#endregion

		#region Private methods

        private string GetRoleImage(string roleIDString)
        {
            string cacheKey = string.Format("RoleImage-Role:{0}-Site:{1}", roleIDString, CSContext.Current.SettingsID);
            string filePath = CSCache.Get(cacheKey) as string;

            if (filePath == null)
            {
                // If no image is found, FindImage() will return an emptry string
                // We still want to cache this so we don't re-check every time this control loads
                filePath = FindImage(roleIDString);
                CSCache.Insert(cacheKey, filePath, CSCache.HourFactor);
            }

            return filePath;
            
        }

		private string FindImage(string roleIDString)
		{
            CSContext context = CSContext.Current;
            string skinImagePath = string.Format("{0}/images/roleicons/{1}", Globals.GetSkinPath(), roleIDString);
            string uploadImagePath = string.Format("{0}/utility/roleicons/{1}", Globals.ApplicationPath, roleIDString);
			string vpath = null;

            // Check site skin for .gif
            vpath = string.Concat(skinImagePath, ".gif");
			if (File.Exists(context.Context.Server.MapPath(vpath)))
				return vpath;

			// Check site skin for .jpg
            vpath = string.Concat(skinImagePath, ".jpg");
            if (File.Exists(context.Context.Server.MapPath(vpath)))
                return vpath;

			// Check site skin for .png
            vpath = string.Concat(skinImagePath, ".png");
            if (File.Exists(context.Context.Server.MapPath(vpath)))
                return vpath;
			
			// Check global role icon upload location for .gif
            vpath = string.Concat(uploadImagePath, ".gif");
            if (File.Exists(context.Context.Server.MapPath(vpath)))
                return vpath;

			// Check global role icon upload location for .jpg
            vpath = string.Concat(uploadImagePath, ".jpg");
            if (File.Exists(context.Context.Server.MapPath(vpath)))
                return vpath;

			// Check global role icon upload location for .png
            vpath = string.Concat(uploadImagePath, ".png");
            if (File.Exists(context.Context.Server.MapPath(vpath)))
                return vpath;

			return string.Empty;
		}

		#endregion

		#region Public properties
		string roleID = null;
		public string RoleID
		{
			get { return roleID; }
			set { roleID = value; }
		}

		bool enableLink = true;
		public bool EnableLink
		{
			get { return enableLink; }
			set { enableLink = value; }
		}

		bool enablePadding = true;
		public bool EnablePadding
		{
			get { return enablePadding; }
			set { enablePadding = value; }
		}

		string target = string.Empty;
		public virtual string Target 
		{
			get 
			{
				return target;		
			}
			set 
			{
				target = value;
			}
		}

		#endregion

	}
}
